 /*
 * AutoSuggest
 * Copyright 2009-2010 Drew Wilson
 * www.drewwilson.com
 * code.drewwilson.com/entry/autosuggest-jquery-plugin
 *
 * Version 1.4   -   Updated: Mar. 23, 2010
 *
 * This Plug-In will auto-complete or auto-suggest completed search queries
 * for you as you type. You can add multiple selections and remove them on
 * the fly. It supports keybord navigation (UP + DOWN + RETURN), as well
 * as multiple AutoSuggest fields on the same page.
 *
 *
 * This AutoSuggest jQuery plug-in is dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){
  $.fn.autoSuggest = function(data, options) {
    var thisObj = $(this);
    var thisClosest = thisObj.closest('div');
    var defaults = {
      asHtmlID: false,
      startText: "请输入要搜索的信息",
      emptyText: "没有找到相关资源",
      preFill: { },
      limitText: "处理人只能为1个人，如需更改，请删除后重新选取",
      selectedItemProp: "title", //name of object property 选中的元素在input中显示的值,如姓名
      selectedValuesProp: "id", //name of object property 选中的元素的实际要传输的值，如id
      searchObjProps: "title", //comma separated list of object property names
      searchRes:{ 'group':'项目', 'company':'公司', 'department':'部门', 'user':'用户', 'file':'文件', 'task':'任务', 'knowledge':'知识', 'calendar':'日历', 'postiton':'职位', 'category':'分类' },
      companyGroupType:1,
      groupId:0,
      queryParam: "q",
      specialRes: "",
      initData:{},
      retrieveLimit: false, //number for 'limit'
      extraParams: "",
      matchCase: false,
      minChars: 0,  // 置为空，为空时搜索常用值
      keyDelay: 40,
      resultsHighlight: true,
      neverSubmit: false,
      selectionLimit: false,
      selectionType: 1,
      currModule:'',
      resultType: 1,
      showResultList: true,
      // 方法
      start: function(){},
      selectionClick: function(elem){},
      selectionAdded: function(elem){},
      selectionRemoved: function(elem){ elem.remove(); },
      formatList: false, //callback function
      beforeRetrieve: function(string){ return string; },
      retrieveComplete: function(data){ return data; },
      resultClick: function(data){return false;},
      resultsComplete: function(){
        if (thisClosest.find(".mCSB_container").length > 0) {
          //thisClosest.find('.searchList').mCustomScrollbar('update');
          thisClosest.find('.searchList').mCustomScrollbar();
        } else if (thisClosest.find(".searchList").length > 0) {
          thisClosest.find('.searchList').mCustomScrollbar();
        }
        //console.log(thisObj, 'qianym');
      }
    };

    //alert(options.initData);
    var opts = $.extend(defaults, options);     
    var d_type = "object";
    var d_count = 0;
    if(typeof data == "string") {
      d_type = "string";
      var req_string = data;
    } else {
      var org_data = data;
      for (k in data) if (data.hasOwnProperty(k)) d_count++;
    }
    
    // 正式开始
    if((d_type == "object" && d_count > 0) || d_type == "string"){
      return this.each(function(x){
        if(!opts.asHtmlID){
          x = x+""+Math.floor(Math.random()*100); //this ensures there will be unique IDs on the page if autoSuggest() is called multiple times
          var x_id = "as-input-"+x;
        } else {
          x = opts.asHtmlID;
          var x_id = x;
        }
        opts.start.call(this);
        
        // 绑定的input输入框
        var input = $(this);
        input.attr("autocomplete", "off").addClass("as-input").attr("id",x_id);
        if ($.isEmptyObject(opts.initData)) {
          input.val(opts.startText)
        }
        // 默认input没有获得焦点
        var input_focus = false;
        
        // 初始化 Setup basic elements and render them to the DOM
        input.wrap('<ul class="as-selections" id="as-selections-'+x+'"></ul>').wrap('<li class="as-original" id="as-original-'+x+'"></li>');
        var selections_holder = $("#as-selections-"+x);
        var org_li = $("#as-original-"+x);
        // 下接选择menu
        var results_holder = $('<div class="as-results" id="as-results-'+x+'"></div>').hide();
        var results_ul01;
        var results_ul;
        if (opts.resultType == 1) {
          results_ul01 =  $('<div class="fl-cont1 float-add-per"></div>');
          results_ul = $('<div class="per-team-box searchList" style="max-height:256px; overflow:hidden;"></div>');
        } else {
          results_ul01 =  $('<div class="fl-cont1"></div>');
          results_ul = $('<div class="tp-list searchList" style="max-height:280px; overflow:hidden;"></div></div>');
        }
        // 选中后的实际值
        var values_input = $('<input type="hidden" class="as-values" name="as_values_'+x+'" id="as-values-'+x+'" />');
        var prefill_value = "";
        // preFill
        if(typeof opts.preFill == "string"){
          var vals = opts.preFill.split(",");          
          for(var i=0; i < vals.length; i++){
            var v_data = {};
            v_data[opts.selectedValuesProp] = vals[i];
            if(vals[i] != ""){
              add_selected_item(v_data, "000"+i);  
            }
          }
          prefill_value = opts.preFill;
        } else {
          prefill_value = "";
          var prefill_count = 0;
          for (k in opts.preFill) if (opts.preFill.hasOwnProperty(k)) prefill_count++;
          if(prefill_count > 0){
            for(var i=0; i < prefill_count; i++){
              var new_v = opts.preFill[i][opts.selectedValuesProp];
              if(new_v == undefined){ new_v = ""; }
              prefill_value = prefill_value+new_v+",";
              if(new_v != ""){
                add_selected_item(opts.preFill[i], "000"+i);
              }
            }
          }
        }
        if(prefill_value != ""){
          //input.val("").css({ 'width':'60px' });
          var lastChar = prefill_value.substring(prefill_value.length-1);
          if(lastChar != ","){ prefill_value = prefill_value+","; }
          values_input.val(","+prefill_value);
          $("li.as-selection-item", selections_holder).addClass("blur").removeClass("selected");
        } else {
          //input.css({ 'width':'120px' })
        }
        
        if (opts.startText.length < 5) {
          //input.width(60);
        }
        
        input.after(values_input);
        selections_holder.click(function(){
          input_focus = true;
          input.focus();
        }).mousedown(function(){ input_focus = false; }).after(results_holder);  //after(results_holder)，初始化搜索列表框

        results_holder.append(results_ul01);
        
        var timeout = null;
        var prev = "";
        var totalSelections = 0;
        var tab_press = false;
        var hideThis = 0;
        
        // Handle input field events
        input.focus(function(){
          //console.log('qian focus value', $(this).val(), values_input.val());
          if($(this).val() == opts.startText && values_input.val() == ""){
            $(this).val("");
            //console.log('qian focus1');
            // 值为空，获得焦点时提供默认值
            if (timeout){ clearTimeout(timeout); }
            timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
          } else if(input_focus){
            $("li.as-selection-item", selections_holder).removeClass("blur");

            if(opts.showResultList){
              //console.log('qian focus2');
              if (timeout){ clearTimeout(timeout); }
              timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
            }
          }
          input_focus = true;
          
          hideThis = 0;
          return true;
        }).blur(function(){
          if($(this).val() == "" && values_input.val() == "" && prefill_value == "" && input_focus){
            $(this).val(opts.startText);
            //$("li.as-selection-item", selections_holder).addClass("blur").removeClass("selected");
            results_holder.hide();
          } else if(input_focus){
            $("li.as-selection-item", selections_holder).addClass("blur").removeClass("selected");
            results_holder.hide();
            
            hideThis = 1;
          }
          //return results_holder.hide();
        }).keydown(function(e) {
          // track last key pressed
          lastKeyPressCode = e.keyCode;
          first_focus = false;
          //console.log(e.keyCode, '-----');
          switch(e.keyCode) {
            case 38: // up
              e.preventDefault();
              moveSelection("up");
              break;
            case 40: // down
              e.preventDefault();
              moveSelection("down");
              break;
            case 8:  // delete
              if(input.val() == ""){              
                var last = values_input.val().split(",");
                last = last[last.length - 2];
                selections_holder.children().not(org_li.prev()).removeClass("selected");
                if(org_li.prev().hasClass("selected")){
                  values_input.val(values_input.val().replace(","+last+",",","));
                  opts.selectionRemoved.call(this, org_li.prev());
                } else {
                  opts.selectionClick.call(this, org_li.prev());
                  org_li.prev().addClass("selected");    
                }
                
                if (values_input.val() == ",") {
                  values_input.val("");
                }
              }
              if(input.val().length == 1){
                //results_holder.hide();
                 //prev = "";
              }
              if($(":visible",results_holder).length > 0){
                if (timeout){ clearTimeout(timeout); }
                timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
              }
              break;
            case 27: // esc
              input.trigger('blur');
              //results_holder.hide();
              //input_focus = false;
              break;
            case 9: 
              //input_focus = false;
              results_holder.hide();
              break;
            case 188:  // tab or comma
              tab_press = true;
              //console.log(input.attr('name'), '=============');
              var i_input = input.val().replace(/(,)/g, "");
              if(i_input != "" && values_input.val().search(","+i_input+",") < 0 && i_input.length >= opts.minChars){  
                e.preventDefault();
                var n_data = {};
                n_data[opts.selectedItemProp] = i_input;
                n_data[opts.selectedValuesProp] = i_input;                                        
                var lis = $("li", selections_holder).length;
                add_selected_item(n_data, "00"+(lis+1));
                input.val("");
                //console.log('qian201311');
              }
            case 13: // return
              tab_press = false;
              var active = $("li.active:first", results_holder);
              if(active.length > 0){
                active.click();
                results_holder.hide();
              }
              if(opts.neverSubmit || active.length > 0){
                e.preventDefault();
              }
              break;
            default:
              // 输入数据（特殊键除处）开始搜索
              if(opts.showResultList){
                //alert($("li.as-selection-item", selections_holder).length+'_'+opts.selectionLimit);
                //console.log('qian0419', $("li.as-selection-item", selections_holder).length)
                if (timeout){ clearTimeout(timeout); }
                timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                
              }
              break;
          }
        });
        
        // do search
        function keyChange() {
          //return false;
          //console.log('qian0419-2', $("li.as-selection-item", selections_holder).length)
          if(opts.selectionLimit && $("li.as-selection-item", selections_holder).length >= opts.selectionLimit && input_focus == 1){
            results_ul.html('<div class="no-message">'+opts.limitText+'</div>');
            results_holder.show();
            return false;
          }
          
          // ignore if the following keys are pressed: [del] [shift] [capslock]
          if (typeof lastKeyPressCode != "undefined") {
            //if( lastKeyPressCode == 46 || (lastKeyPressCode != 27 && lastKeyPressCode != 13 && lastKeyPressCode > 8 && lastKeyPressCode < 32) ){ return results_holder.hide(); }
          }
          var string = input.val().replace(/[\\]+|[\/]+/g,"");
          if (string != "" && string == prev && !$.inArray(opts.specialRes, [4, 5, 6, 7, 8])) {
            //console.log('qian 999');
            return;
          } 
          //console.log('dong 00');
          prev = string;
          if (string.length >= opts.minChars) {
            selections_holder.addClass("loading");
            if(d_type == "string"){
              var limit = "";
              if(opts.retrieveLimit){
                limit = "&limit="+encodeURIComponent(opts.retrieveLimit);
              }
              if(opts.beforeRetrieve){
                string = opts.beforeRetrieve.call(this, string);
              }
              var new_data;
              if (ace.search && $.inArray(parseInt(opts.specialRes), [2, 3, 4, 5, 6, 9]) != -1) {
                 // opts.companyGroupType 1:公司内部， 2：公司外部
                 var localData = ace.search.common_search(string, opts.specialRes, opts.companyGroupType, opts.groupId);
                 d_count = 0;
                 //console.log(localData, 'wd');
                 new_data = opts.retrieveComplete.call(this, localData);
                 for (k in new_data) if (new_data.hasOwnProperty(k)) d_count++;
                 if (d_count == 0 && prev == '') {
                   return false;
                 } else {
                   processData(new_data, string);
                 }
              } else {
                  var postUrl;
                  if (opts.specialRes != "") {
                    postUrl = req_string+"?res="+opts.specialRes+'&curr_module='+opts.currModule+'&'+opts.queryParam+"="+encodeURIComponent(string)+limit+opts.extraParams;
                  } else {
                    postUrl = req_string+"?"+opts.queryParam+"="+encodeURIComponent(string)+limit+opts.extraParams;
                  }
                  // 是否有额外的参数------------
                  // 选择了某项目后，筛选该项目下的人
                  if (input.attr('data-group-id') > 0) {
                    postUrl += '&group_id='+input.attr('data-group-id');
                  }
                  // 多级分类选择了父分类后，筛选该分类下的子分类
                  if (input.attr('data-category-id') > 0) {
                    postUrl += '&parent_category_id='+input.attr('data-category-id');
                  }
                  
                  $.getJSON(postUrl, function(data){ 
                    d_count = 0;
                    //console.log(data);
                    new_data = opts.retrieveComplete.call(this, data);
                    for (k in new_data) if (new_data.hasOwnProperty(k)) d_count++;
                    if (d_count == 0 && prev == '') {
                      return false;
                    } else {
                      processData(new_data, string);
                    }
                  });
              }
            } else {
              if(opts.beforeRetrieve){
                string = opts.beforeRetrieve.call(this, string);
              }
              processData(org_data, string);
            }
          } else {
            selections_holder.removeClass("loading");
            results_holder.hide();
          }
        }

        var num_count = 0;
        // 用搜索结果拼装下拉菜单
        function processData(data, query){
          
          // 如果不区分大小写，则全转为小写
          if (!opts.matchCase){ query = query.toLowerCase(); }
          // 取得的种类
          var mathTypeNum   = 0;
          // 取得的数据数量
          var matchCount = 0;
          
          //results_holder.html(results_ul.html("")).hide();
          results_ul01.html(results_ul.html(""));
          results_holder.hide();
          var num = 0;
          
          if (opts.specialRes == 2 || opts.specialRes == 9) {
            
            // 临地取出部门数据列表，组装好数据后附加到最后面
            var tmpDepartment = [];
            if (data.department) {
              tmpDepartment = data.department;
              delete data.department;
            }
            
            // 加一个全公司
            data.company = [{ 'id':-100, 'resType':'company', 'title':'全公司所有成员'}];
            // 加一个当前项目
            if (opts.specialRes == 9) {
              var tmpGroupId = input.attr('data-group-id');
              if (tmpGroupId) {
                data.group = [{ 'id':tmpGroupId, 'resType':'group', 'title':'当前项目所有成员'}];
              }
            }
            
            if (tmpDepartment.length > 0) {
              data.department = tmpDepartment;
            }
          }
          
          //console.log(data, 'qiany20130520');
          for (var i in data) {
            // 过滤无需的搜索
            if (opts.searchRes[i] == "undefined") {
              continue;
            }
            
            var formattedOuter = '';
            if (opts.resultType == 1) {
              formattedOuter = '<div class="oneTeam team1 clearfix">\
                <div class="team-name team-name2 left">';
              if (i == 'user') {
                formattedOuter += '<i class="icon-per"></i>';
              } else if (i == 'group') {
                formattedOuter += '<i class="icon-team"></i>';
              } else {
                formattedOuter += '<i class="icon-'+i+'"></i>';
              }
                  
              formattedOuter += '<span>'+opts.searchRes[i]+'</span>\
                 </div>\
                <ul class="team-per team-per2">\
                </ul></div></div>';  
            } else {
              formattedOuter = '<div class="oneTeam team1">'+
                '<div class="team-name"><span>'+opts.searchRes[i]+'</span></div>'+
                '<ul class="team-per">'+
                '</ul></div></div>';
            }

            results_ul.append(formattedOuter);
            
            // 每种类型取得的数据数量
            var matchSingleCount = 0;
            
            // i相当于user,group,department等
            // j相当于0,1,2,3等
            // data[i][j][name]即取得所需值
            for (var j in data[i]) {
              num_count++;
              //console.log(i, num_count, 'qiany20130325');
              //console.log(i, j, data[i][j]);
              if (isNaN(j)) {
                continue;
              }
              var forward = false;
              data[i][j].resType = i;
              if (opts.searchObjProps == "value") {
                var str = data[i][j].value;
              } else {
                var str = "";
                var names = opts.searchObjProps.split(",");
                for (var y=0; y<names.length; y++) {
                  var name = $.trim(names[y]);
                  str = str+data[i][j][name]+" ";
                }
              }
              
              if(str){
                if (!opts.matchCase){ str = str.toLowerCase(); }
                /*str.search(query) != -1 && */
                if(values_input.val().search(","+data[i][j].resType+'_'+data[i][j][opts.selectedValuesProp]+",") == -1){
                  forward = true;
                }
              }

              if (forward){
                var tmpLi = '<li class="as-result-item" id="as-result-item-'+num+'"></li>';
                var formatted = $(tmpLi).click(function(){
                    // 取绑定的数据
                    var raw_data = $(this).data("data");
                    var number = raw_data.num;
                    if($("#as-selection-"+number, selections_holder).length <= 0 && !tab_press){
                      var data = raw_data.info;
                      input.val("").focus();
                      prev = "";
                      //console.log('1212', number);
                      if (opts.selectionType == 2) {
                        opts.resultClick.call(this, raw_data);
                      } else {
                        add_selected_item(data, number);  
                        results_holder.hide();
                      }
                    }
                    tab_press = false;
                  }).mousedown(function(){ input_focus = false; }).mouseover(function(){
                    $("li", results_ul).removeClass("active");
                    $(this).addClass("active");
                    
                    //.data('data', { })li上绑定数据
                  }).data("data",{info: data[i][j], num: num_count});
               //console.log(data);
               //console.log(data[i][j]);
                var this_data = $.extend({},data[i][j]);
                if (!opts.matchCase){ 
                  var regx = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + query + ")(?![^<>]*>)(?![^&;]+;)", "gi");
                } else {
                  var regx = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + query + ")(?![^<>]*>)(?![^&;]+;)", "g");
                }
                
                if(query != "" && opts.resultsHighlight){
                  //console.log(opts);
                  //console.log(opts.selectedItemProp, this_data[opts.selectedItemProp]);
                  //console.log(this_data, data[i][j]);
                  this_data[opts.selectedItemProp] = this_data[opts.selectedItemProp].replace(regx,"<em>$1</em>");
                }
                
                var tmpLiInner = '';
                if (i == 'user') {
                  tmpLiInner += '<img width=30 src="'+siteUrl+this_data.avatar+'" alt="">';
                } else {
                  //tmpLiInner += '<img src="'+siteUrl+'/images/task/heads04.jpg" alt="">';
                }

                tmpLiInner += '<p class="name-all fs12">'+
                    '<span class="name2">'+this_data[opts.selectedItemProp]+'</span>';
                if (i == 'user') {
                  tmpLiInner += '<span>'+this_data['position']+'</span>';
                } else {
                  //tmpLiInner += '<span>设计经理</span>';
                }
                tmpLiInner += '</p>';
                
                if(!opts.formatList){
                  //'<span style="color:red;">'+opts.searchRes[i]+':</span> '
                  formatted = formatted.html(tmpLiInner);
                } else {
                  formatted = opts.formatList.call(this, this_data, formatted);
                }
                results_ul.children().last().find('ul').append(formatted);
                delete this_data;
                
                // 总匹配数量加1
                matchCount++;
                // 单个类型的匹配数量加1 (如：项目数加1，员工数加1)
                matchSingleCount ++;
                
                if (opts.resultType == 1 && opts.specialRes != 1) {
                  if (matchSingleCount == 3) {
                    var tmpLiShowMore = $('<li class="as-result-item showMore"></li>');
                    tmpLiShowMore.click(function(){
                      input.val("").focus();
                      prev = "";
                      
                      $(this).nextAll('li').removeClass('hidden');
                      $(this).addClass('hidden').remove();
                      if (thisClosest.find(".searchList").length > 0) {
                        thisClosest.find('.searchList').mCustomScrollbar('update');
                      }
                    }).mousedown(function(){ input_focus = false; }).mouseover(function(){
                      $("li", results_ul).removeClass("active");
                      $(this).addClass("active");
                      
                      //.data('data', { })li上绑定数据
                    }).html('<p class="name-all fs12"><span class="name2">查看更多</span></p>');
                    results_ul.children().last().find('ul').append(tmpLiShowMore);
                  }
                  if (matchSingleCount >= 4) {
                    formatted.addClass('hidden');
                  }
                }
                
                if(opts.retrieveLimit && opts.retrieveLimit == matchCount ){ break; }
              }
              
              num++;
            }
          }
          results_ul.children().each(function(i){
            if ($(this).find('li').length == 0) {
              $(this).remove();
            }
          });
            //////////////////////////////
          //}
          selections_holder.removeClass("loading");
          // 如果搜索结果为空
          if(matchCount <= 0){
            results_ul.html('<div class="no-message">'+opts.emptyText+'</div>');
          } else {
            $('.team-per li')
          }
          // 搜索结果展示宽度
          var resultBoxWidth = selections_holder.outerWidth();
          //console.log(resultBoxWidth, 'resultwidth');
          if (resultBoxWidth > 398) {
            resultBoxWidth = 398;
          }
          if (!selections_holder.parent().hasClass("search-input-box")) {
              results_ul.css("width", resultBoxWidth);
          }
          if (opts.resultType == 1 && !input.hasClass('commonSearch')) {
            results_ul01.css("width", resultBoxWidth);
          }
          results_holder.show();
          $("li:visible:first", results_holder).addClass('active');
          opts.resultsComplete.call(this);
          
          if (input_focus == 0) {
            results_holder.hide();
            return false;
          }
        }
        
        // 选中某元素时，表单中加入数据
        function add_selected_item(data, num){
          if (values_input.val() == "") {
            values_input.val(','+data.resType+'_'+data[opts.selectedValuesProp]+",");
          } else {
            values_input.val(values_input.val()+data.resType+'_'+data[opts.selectedValuesProp]+",");
          }
          var item = $('<li class="as-selection-item" id="as-selection-'+num+'"></li>').click(function(){
              opts.selectionClick.call(this, $(this));
              selections_holder.children().removeClass("selected");
              $(this).addClass("selected");
            }).mousedown(function(){ input_focus = false; });
          var close = $('<a class="as-close">&times;</a>').click(function(){
              values_input.val(values_input.val().replace(","+data.resType+'_'+data[opts.selectedValuesProp]+",",","));
              if (values_input.val() == ",") {
                values_input.val("");
              }
              opts.selectionRemoved.call(this, item);
              input_focus = true;
              input.focus();
              return false;
            });
          var iconHtml = '';
          if (data.resType == 'user') {
            iconHtml = '<i class="icon-per2"></i>';
          } else if (data.resType == 'group') {
            iconHtml = '<i class="icon-team2"></i>';
          } else {
              iconHtml = '<i class="icon-'+data.resType+'2"></i>';
          }
          //console.log(data, 1);
          org_li.before(item.html(data[opts.selectedItemProp]).prepend(iconHtml).prepend(close));
          opts.selectionAdded.call(this, org_li.prev());  
        }
        
        // 上下键移动鼠标位置
        function moveSelection(direction){
          
          if($(":visible",results_holder).length == 0){
            return false;
          }

          var lis = $("li:visible", results_holder);
          if(direction == "down"){
            var start = lis.eq(0);
          } else {
            var start = lis.filter(":last");
          } 
          
          var active = $("li.active:visible:first", results_holder);
          if(active.length > 0){
            if(direction == "down"){
              if (active.next().not($(".hidden")).length > 0) {
                start = active.next().not($(".hidden"));
              } else if (active.closest('.oneTeam').next().length > 0) {
                start = active.closest('.oneTeam').next().find('li:visible:first');
              }
            } else {
              start = active.prev();
              if (active.prev().length > 0) {
                start = active.prev();
              } else if (active.closest('.oneTeam').prev().length > 0) {
                start = active.closest('.oneTeam').prev().find('li:visible:last');
              }
            }
          }
          lis.removeClass("active");
          start.addClass("active");
        }
        
        //alert(opts.initData.title);
        // 初始化数据
        if (!$.isEmptyObject(opts.initData) && opts.specialRes > 0 && opts.specialRes != 1) {
          //alert(opts.initData.title);
          if (typeof opts.initData.id != "undefined") {
            add_selected_item(opts.initData, 1);
            num_count++;
          } else {
            $.each(opts.initData, function(_i1, _n1){
              add_selected_item(_n1, 1);
              num_count++;
            });
          }
        }
      });
    }
  }
})(jQuery);